package com.zengyan.gd.service.impl;

import com.zengyan.gd.core.ServiceException;
import com.zengyan.gd.form.GetUserForm;
import com.zengyan.gd.form.OrgLoginForm;
import com.zengyan.gd.model.Event;
import com.zengyan.gd.model.Organization;
import com.zengyan.gd.model.Relationship;
import com.zengyan.gd.model.SignUp;
import com.zengyan.gd.model.User;
import com.zengyan.gd.repository.EventRespository;
import com.zengyan.gd.repository.OU_Respository;
import com.zengyan.gd.repository.OrganizationRepository;
import com.zengyan.gd.repository.SignUpRespository;
import com.zengyan.gd.repository.UserRepository;
import com.zengyan.gd.service.OrganizationService;
import com.zengyan.gd.utils.ExportExcel;
import com.zengyan.gd.utils.ImageType;
import com.zengyan.gd.utils.ImageUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;


/**
 *
 */
@Service
public class OrganizationServiceImpl implements OrganizationService {

    @Autowired
    OrganizationRepository mOrgRepository;

    @Autowired
    OU_Respository mOU_Respository;

    @Autowired
    UserRepository mUserRepository;

    @Autowired
    EventRespository mEventRespository;

    @Autowired
    SignUpRespository mSignUpRepository;


    @Override
    public Organization register(Organization organization) throws Exception {
        Organization org = mOrgRepository.findByEmail(organization.getEmail());
        if (org != null) {
            throw new ServiceException("此邮箱已经注册过");
        }
        return mOrgRepository.save(organization);
    }

    @Override
    public List<Organization> findAllOrgs() {
        return mOrgRepository.findAll();
    }

    @Override
    public Organization login(OrgLoginForm loginForm) throws Exception {
        Organization organization = mOrgRepository.findByEmail(loginForm.getEmail());
        if (organization == null) {
            throw new ServiceException("此组织不存在");
        }
        if (!loginForm.getPassword().equals(organization.getPassword())) {
            throw new ServiceException("密码错误");
        }
        return organization;
    }

    @Override
    public Organization updateImage(int org_id, MultipartFile file, ImageType type) throws Exception {

        String url = ImageUtils.saveOrgImage(file, type, org_id);
        Organization organization = mOrgRepository.findOne(org_id);
        switch (type) {
            case orgAvater:
                organization.setAvatarUrl(url);
                break;
            case orgBg:
                organization.setBgUrl(url);
                break;
        }
        mOrgRepository.save(organization);
        return organization;
    }


    @Override
    public void saveUsersFormFile(int id, List<String> stuNumList) {
        List<Relationship> alreadly = mOU_Respository.findByOrgId(id);
        mOU_Respository.delete(alreadly);

        List<Relationship> list = new ArrayList<>();
        for (String stunum : stuNumList) {
            Relationship relationship = new Relationship();
            relationship.setOrgId(id);
            relationship.setStudentNum(stunum);
            list.add(relationship);
        }
        mOU_Respository.save(list);
    }

    @Override
    public GetUserForm getMyUsers(int id) {
        GetUserForm getUserForm = new GetUserForm();
        List<Relationship> relationships = mOU_Respository.findByOrgId(id);
        for (Relationship relationship : relationships) {
            User user = mUserRepository.findByStudentNum(relationship.getStudentNum());
            if (user != null) {
                getUserForm.getUsers().add(user);
            } else {
                getUserForm.getUnRegisterUsers().add(relationship.getStudentNum());
            }
        }
        return getUserForm;
    }

    @Override
    public Boolean hasOrg(int id) throws Exception {

        return mOrgRepository.getOne(id) == null ? false : true;
    }

    @Override
    public Event createEvent(Event event) throws Exception {

        return mEventRespository.save(event);
    }

    @Override
    public List<User> findUsersByEvent(int event_id) throws Exception {
        List<SignUp> signUps = mSignUpRepository.findByEventId(event_id);
        List<User> users = new ArrayList<>();
        for (SignUp signUp : signUps) {
            users.add(mUserRepository.findByStudentNum(signUp.getStuNum()));
        }

        return users;
    }

    @Override
    public void deleteEvent(int id) throws Exception {
        mEventRespository.delete(id);
    }

    @Override
    public List<Event> getEventsById(int id) throws Exception {
        return mEventRespository.findByOrgId(id);
    }

    @Override
    public GetUserForm addMember(int org_id, String stunum) {
        Relationship relationship = new Relationship();
        relationship.setStudentNum(stunum);
        relationship.setOrgId(org_id);
        mOU_Respository.save(relationship);

        return getMyUsers(org_id);
    }

    @Override
    public GetUserForm deleteMember(int org_id, String stunum) {
        Relationship relationship = mOU_Respository.findByStudentNumAndOrgId(stunum, org_id);
        if (relationship == null) throw new ServiceException("找不到对于的member");

        mOU_Respository.delete(relationship);
        return getMyUsers(org_id);
    }

    @Override
    public List<User> searchMember(int org_id, String message) {
        List<User> userList = new ArrayList<>();

        GetUserForm getUserForm = getMyUsers(org_id);
        List<User> orgUsers = getUserForm.getUsers();
        for (User user : orgUsers) {
            if (user.getName().contains(message)){
                    userList.add(user);
            }
        }
        return userList;
    }

    @Override
    public Organization getOrgInfo(int org_id) {
        return mOrgRepository.getOne(org_id);
    }

    @Override
    public List<User> getPeopleSignUpInEvent(int event_id) {
        List<SignUp> signUps = mSignUpRepository.findByEventId(event_id);
        List<User> list = new ArrayList<>();
        for (SignUp signUp : signUps) {
            list.add(mUserRepository.findByStudentNum(signUp.getStuNum()));
        }
        return list;
    }

    @Override
    public String createSignUpExcel(int event_id) throws Exception {
        Event event = mEventRespository.findOne(event_id);
        List<User> list = getPeopleSignUpInEvent(event_id);
        List<Object[]>  dataList = new ArrayList<Object[]>();
        String title = event.getTitle()+" 人员名单";
        String[] rowsName = new String[]{"序号","学号","姓名"};
        Object[] objs = null;
        for (int i = 0; i < list.size(); i++) {
            User user = list.get(i);
            objs = new Object[rowsName.length];
            objs[0] = i;
            objs[1] = user.getStudentNum();
            objs[2] = user.getName();

            dataList.add(objs);
        }
        String filename = event.getId() + "-" + event.getTitle() + "-" + "报名表";
        ExportExcel ex = new ExportExcel(filename,title, rowsName, dataList);
        return ex.export();
    }

    @Override
    public Organization updateDesc(int org_id, String desc) throws Exception {
        Organization organization = mOrgRepository.findOne(org_id);
        organization.setDescription(desc);
        mOrgRepository.save(organization);
        return organization;
    }

    @Override
    public Event updateEventImage(int event_id, MultipartFile file) throws Exception{
        Event event = mEventRespository.findOne(event_id);
        String url = ImageUtils.saveEventImage(file, event_id);
        event.setBgUrl(url);
        return  mEventRespository.save(event);
    }


}
